package com.abbas.CayTcore

import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import com.abbas.CayTcore.entity.NetBean
import com.abbas.smartCity.retroft.ICallback2
import com.abbas.smartCity.retroft.RetrofitCallback2Dsl
import io.reactivex.Single
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import retrofit2.Call

inline fun <reified C> Context.startActivity(clazz: Class<C>,block: Intent.() -> Unit = {}){
    startActivity(Intent(this,clazz).also(block))
}

inline fun <reified C> Fragment.startActivity(clazz: Class<C>,block: Intent.() -> Unit = {}){
    requireActivity().startActivity(Intent(requireContext(),clazz).also(block))
}

fun <T> Single<T>.subscribeDbResult(onSuccess: (data: T) -> Unit,onnFailure: (e: Throwable) -> Unit){
    subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe (object : SingleObserver<T>{
            override fun onSubscribe(d: Disposable) {

            }

            override fun onSuccess(t: T) {
                onSuccess(t)
            }

            override fun onError(e: Throwable) {
                onnFailure(e)
            }
        })
}

fun <T> Call<NetBean<T>>.start(dsl: RetrofitCallback2Dsl<T>.() -> Unit): RetrofitCallback2Dsl<T> {
    val actDsl = RetrofitCallback2Dsl<T>().apply(dsl)
    enqueue(object : ICallback2<T>(){
        override fun onSuccess(call: Call<NetBean<T>>, data: NetBean<T>) {
            actDsl.onSuccess?.invoke(data)
        }

        override fun onServerError() {
            actDsl.onNetError.invoke()
        }

        override fun onRequestError(call: Call<NetBean<T>>, msg: String) {
            actDsl.onRequestError?.invoke(msg)
        }
    })
    return actDsl
}

